import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Layout from '../components/Layout.vue'
import Home from '../components/Home.vue'
import ClassroomList from '../components/ClassroomList.vue'
import QRCodeAttendance from '../components/QRCodeAttendance.vue'
import LocationAttendance from '../components/LocationAttendance.vue'
import GestureAttendance from '../components/GestureAttendance.vue'
import CodeAttendance from '../components/CodeAttendance.vue'
import QuickAttendance from '../components/QuickAttendance.vue'
import AttendanceTaskList from '../components/AttendanceTaskList.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: '/home'
      },
      {
        path: 'home',
        name: 'Home',
        component: Home
      },
      {
        path: 'classroom',
        name: 'ClassroomList',
        component: ClassroomList
      },
      {
        path: 'attendance/qrcode',
        name: 'QRCodeAttendance',
        component: QRCodeAttendance
      },
      {
        path: 'attendance/location',
        name: 'LocationAttendance',
        component: LocationAttendance
      },
      {
        path: 'attendance/gesture',
        name: 'GestureAttendance',
        component: GestureAttendance
      },
      {
        path: 'attendance/code',
        name: 'CodeAttendance',
        component: CodeAttendance
      },
      {
        path: 'attendance/quick',
        name: 'QuickAttendance',
        component: QuickAttendance
      },
      {
        path: 'attendance/tasks',
        name: 'AttendanceTaskList',
        component: AttendanceTaskList
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')

  if (to.meta.requiresAuth && !token) {
    // 需要登录但未登录，重定向到登录页
    next('/login')
  } else if (to.path === '/login' && token) {
    // 已登录但访问登录页，重定向到首页
    next('/home')
  } else {
    next()
  }
})

export default router

